package com.test.demo.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMqConfig {

    @Value("${rabbit.exchange}")
    private String exchange;

    @Value("${rabbit.queue}")
    private String queue;

    //定义正常交换机
    @Bean("topic_exchange")
    Exchange getExchange(){
        return ExchangeBuilder.topicExchange(exchange).durable(true).build();
    }

    //定义正常队列
    @Bean("queue1")
    Queue getQueue(){
        //这里的ttl属性为为队列设置 过期时间10000毫秒 队列长度100 因为我在这里设置了ttl过期时间和队列长度那么极有可能信息会成为死信 所以在这里绑定死信交换机
        //后面的两个参数为绑定死信交换机和指定路由key 因为这里的死信交换机的路由key为“dlx.*”,所以指定key为“dlx.random”
        return QueueBuilder.durable(queue).ttl(10000).maxLength(100).deadLetterExchange("topic_exchange_dlx").deadLetterRoutingKey("dlx.random").build();
    }

    //定义死信交换机
    @Bean("topic_exchange_dlx")
    Exchange getExchangeDlx(){
        return ExchangeBuilder.topicExchange("topic_exchange_dlx").durable(true).build();
    }

    //定义死信队列
    @Bean("queue1_dlx")
    Queue getQueueDlx(){
        //这里的ttl属性为为队列设置 过期时间10000毫秒 队列长度100
        return QueueBuilder.durable("queue1_dlx").build();
    }


    //交换机与队列绑定
    @Bean
    Binding bingQueueExchangeOrder(@Qualifier("topic_exchange") Exchange exchange,@Qualifier("queue1") Queue queue){
        return BindingBuilder.bind(queue).to(exchange).with("order.*").noargs();
    }

    @Bean
    Binding bingQueueExchangeUser(@Qualifier("topic_exchange") Exchange exchange,@Qualifier("queue1") Queue queue){
        return BindingBuilder.bind(queue).to(exchange).with("user.*").noargs();
    }

    //死信交换机与死信队列绑定
    @Bean
    Binding bingQueueDlxExchangeDlx(@Qualifier("topic_exchange_dlx") Exchange exchange,@Qualifier("queue1_dlx") Queue queue){
        return BindingBuilder.bind(queue).to(exchange).with("dlx.*").noargs();
    }
}
